import { ConfigService } from '@nestjs/config'
import { PrismaClient } from '@prisma/client'




export async function pageData<T>(model: string, query: any): Promise<Result.pageData<T>> {
  const config = new ConfigService()
  const prisma = new PrismaClient()
  const row = config.get('PAGE_ROW')
  const params = {} as T
  Object.keys(query).forEach(key => {
    if(key !== 'page' && query[key]) params[key] = query[key]
  }) 
  const dataList = await prisma[model].findMany({
    where: {
      ...params
    },
    skip: (+query.page - 1) * row,
    take: +row
  }) as T[]
  const total = await prisma[model].count()
  // const total = dataList.length
  return {
    currentPage: +query.page,
    pageRow: +row,
    total,
    totalPage: Math.ceil(total / row),
    data: dataList
  }
}